package com.hdu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.hdu.common.Result;
import com.hdu.common.ResultCode;
import com.hdu.dao.UserDao;
import com.hdu.dto.PhoneRegisterDto;
import com.hdu.dto.UserDto;
import com.hdu.exception.CustomException;
import com.hdu.pojo.User;
import com.hdu.util.RegexUtils;
import com.hdu.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.hdu.service.UserService;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hdu.pojo.User.Role.USER;
import static com.hdu.util.RedisConstants.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public boolean deleteUser(Integer id) {
        return userDao.deleteUserById(id);
    }

    @Override
    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    @Override
    public User getUserByName(String username) {
        return userDao.getUserByName(username);
    }

    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    @Override
    public int countByUsername(String username) {
        int count = userDao.countByUsername(username);
        return count;
    }

    @Override
    public boolean login(String username, String password) {

        User user = userDao.getUserByName(username);

        if (user == null) {
            throw new CustomException("用户不存在请先注册!");
        }

        if (!user.getPassword().equals(password)) {
            throw new CustomException("用户名或者密码错误！");
        }

        String token = (String)redisTemplate.opsForHash().get(LOGIN_USER_KEY + user.getId(), "token");

        if(StringUtils.isBlank(token)){
            token=String.valueOf(user.getId());
        }

        // 7.3.存储
        String tokenKey = LOGIN_USER_KEY + token;

        HashMap<String, Object> userMap = new HashMap<>();
//        User.Role role = user.getRole();
        userMap.put("role",user.getRole().toString());
        userMap.put("id",user.getId().toString());
        userMap.put("username",user.getUsername());
        redisTemplate.opsForHash().putAll(tokenKey, userMap);
        // 7.4.设置token有效期
        redisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;

    }

    @Override
    public boolean register(String username, String password) {
        User user = userDao.getUserByName(username);

        if (user != null) {
            throw new CustomException("用户已经存在，请更换名称！");
        }

        User insertingUser = new User();
        insertingUser.setEmail("123456@qq.com");
        insertingUser.setCreateTime(LocalDateTime.now());
        insertingUser.setRole(USER);
        insertingUser.setUsername(username);
        insertingUser.setPassword(password);

        boolean insertSucceed = userDao.addUser(insertingUser);

        if (!insertSucceed) {
            throw new CustomException("注册失败！");
        }

        return true;
    }

    @Override
    public boolean generateCode(String phone, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            throw new CustomException("手机号格式错误！");
        }
        // 3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4.保存验证码到 session
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 5.发送验证码
        log.info("发送短信验证码成功，验证码：{}", code);
        return true;
    }

    @Override
    public boolean confirmCode(String phone, String code) {
        if (phone.isEmpty() || code == null) {
            throw new CustomException("手机号为空或者验证码为空！");
        }

        String rightCode = (String) redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);

        if (rightCode == null) {
            throw new CustomException("验证码查询失败！");
        }

        if (!String.valueOf(code).equals(rightCode)) {
            throw new CustomException("验证码错误！");
        }

        User userExisted = userDao.getUserByPhone(phone);
        if (userExisted != null) {
            System.out.println(userExisted.getUsername());
            throw new CustomException("手机号已被注册！");
        }

        User user = new User();
        user.setPassword(DigestUtil.md5Hex("123"));
        user.setRole(USER);
        user.setEmail("123456@qq.com");
        user.setCreateTime(LocalDateTime.now());
        user.setUsername(USER_SIGN_KEY + RandomUtil.randomString(6));
        user.setPhone(phone);
        userDao.addUser(user);

        return true;
    }

    @Override
    public Result<String> loginByPhone(String phone, String code) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            throw new CustomException("手机号格式错误！");
        }

        User user = userDao.getUserByPhone(phone);
        if(user==null){
            throw new CustomException("该手机号未注册！");
        }

        String rightCode= (String)redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);

        if(rightCode==null){
            throw new CustomException("验证码不存在！");
        }
//        System.out.println("rightCode:"+rightCode);
//        System.out.println("code:" + code);
        boolean equals = rightCode.equals(String.valueOf(code));

        if(!equals){
            throw new CustomException("验证码错误！");
        }

        // 先从redis中获取该用户的token
        String token = (String)redisTemplate.opsForHash().get(LOGIN_USER_KEY + user.getId(), "token");

        // 如果token为空,才重新生成一个新的token
        if (StringUtils.isBlank(token)) {
            token = String.valueOf(user.getId());
        }


        // 7.保存用户信息到 redis中
        // 7.1.随机生成token，作为登录令牌
//        token = user.getId()+UUID.randomUUID().toString(true);



        // 7.2.将User对象转为HashMap存储
        UserDto userDTO = BeanUtil.copyProperties(user, UserDto.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        // 7.3.存储
        String tokenKey = LOGIN_USER_KEY + token;
        redisTemplate.opsForHash().putAll(tokenKey, userMap);
        // 7.4.设置token有效期
        redisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return new Result<>(ResultCode.SUCCESS,"登录成功，正在跳转~");
    }

}

